<template>
	<transition name="todo" appear>
		<li>
			<label>
				<!-- 给一个checkbox设置是否选中，就用v-bind绑定check属性的值 -->
				<input type="checkbox" :checked="todo.done" @change="checkedMethod(todo.id)" />
				<span v-show="!todo.isEdit">{{ todo.name }}</span>
				<input type="text" v-show="todo.isEdit" @blur="editTask(todo, $event)" ref="editInput"
					@keydown.enter="editTask(todo, $event)">
			</label>
			<button class="btn btn-danger" @click="handlerDelete(todo.id)">删除</button>
			<button class="btn btn-edit" @click="handleEdit(todo)" v-show="!todo.isEdit">编辑</button>
		</li>
	</transition>
</template>

<script>
export default {
	name: "MyItem",
	// props子组件接受父组件传递的属性或函数
	props: ['todo'],
	methods: {
		//勾选
		checkedMethod(id) {
			// 触发全局事件总线上的事件去传递数据
			this.$bus.$emit("checkDone", id)
		},
		//删除
		handlerDelete(id) {
			if (confirm("确认要删除吗")) {
				this.$bus.$emit("todoDelete", id)
			}

		},
		//编辑按钮点击
		handleEdit(todo) {
			if (todo.isEdit === undefined) {
				this.$set(todo, "isEdit", true)
			} else {
				todo.isEdit = true
			}
			this.$refs.editInput.value = todo.name
			// 下一次渲染模板时执行回调函数
			this.$nextTick(() => {
				this.$refs.editInput.focus()
			})
		},
		//编辑内容确认
		editTask(todo, event) {
			if (!event.target.value.trim()) {
				this.$refs.editInput.value = todo.name
				return alert("输入不能为空!")
			}
			todo.isEdit = false
			this.$bus.$emit("todoEdit", todo.id, event.target.value)
		}
	}
}
</script>

<style scoped>
/*item*/
li {
	list-style: none;
	height: 36px;
	line-height: 36px;
	padding: 0 5px;
	border-bottom: 1px solid #ddd;
	font-size: 12px;
}

li label {
	float: left;
	cursor: pointer;
}

li label li input {
	vertical-align: middle;
	margin-right: 6px;
	position: relative;
	top: -1px;
}

li button {
	float: right;
	display: none;
	margin-top: 3px;
}

li:before {
	content: initial;
}

li:last-child {
	border-bottom: none;
}

li:hover {
	background-color: #ddd;
}

li:hover button {
	display: block;
}

.todo-enter-active {
	animation: anme 0.5s linear;
}

.todo-leave-active {
	animation: anme 0.5s reverse;
}

@keyframes anme {
	from {
		transform: translate(100%);
	}

	to {
		transform: translate(0);
	}
}
</style>